#ifndef EEGDEVICE_H
#define EEGDEVICE_H

#include "BioSignalDevice.h"
#include <QSerialPort>
#include <QTimer>
#include <QVector>
#include <QMutex>
#include <QThread>
#include <complex>
#include "DatabaseWorker.h"

class EEGDevice : public BioSignalDevice
{
    Q_OBJECT

public:
    explicit EEGDevice(QObject *parent = nullptr);
    ~EEGDevice() override;

    // 设备信息
    QString getDeviceInfo() const override;
    void setNotchFilterEnabled(bool enabled);
    bool isNotchFilterEnabled() const;
    void setNotchFrequency(double frequency);
    double getNotchFrequency() const;
    void setNotchBandwidth(double bandwidth);
    double getNotchBandwidth() const;

    void setHighpassFilterEnabled(bool enabled);
    bool isHighpassFilterEnabled() const;

    // 连接管理
    bool connect() override;
    bool disconnect() override;
    bool isConnected() const;

    // 数据采集
    bool startAcquisition() override;
    bool stopAcquisition() override;
    bool isAcquiring() const;


    // CSV文件处理
    bool processCSVFile(const QString& inputFilePath, const QString& outputFilePath);

signals:
    void csvProcessingProgress(int percent);
    void csvProcessingFinished(bool success, const QString& message);

private slots:
    void readSerialData();
    void processAccumulatedData();
    void updateVisualizationFromDB();
    void updateVisualizationFromBuffer();

private:
    // FFT滤波器实现
    void initializeFilters();
    QVector<double> applyBandpassFilter(const QVector<double> &data,
                                        double lowCutoff,
                                        double highCutoff,
                                        double samplingRate,int channelIndex = -1);
    void fft(QVector<std::complex<double>> &x, bool inverse);
    QVector<QVector<double>> processEegData(const QVector<QVector<double>>& inputData);
    //陷波滤波器
    QVector<double> applyNotchFilter(const QVector<double>& data,
                                     double notchFreq,
                                     double bandwidth,
                                     double samplingRate);
    // 帧解析
    QVector<double> parseFrame(const QByteArray &frame);
    int decimalArrayToHexNumber(const QVector<int> &decimalArray);
    double rawToVoltage(int rawData, double vref = 4.5, double gain = 24.0);

    // 数据保存
    void saveDataToCSV();

    // CSV文件处理
    QVector<QVector<double>> loadCSVData(const QString& filePath);
    bool saveCSVData(const QVector<QVector<double>>& data, const QString& filePath);

    // 串口通信
    QSerialPort* m_serialPort;
    QString m_portName;
    int m_baudRate;

    // 数据缓冲区
    QByteArray m_frameBuffer;
    QVector<double> m_voltageBuffer;
    QVector<QVector<double>> m_accumulatedData;
    QVector<QVector<double>> m_referenceData;
    QMutex m_dataMutex;

    // 数据存储
    QVector<QVector<unsigned char>> m_rawData;
    QVector<QVector<double>> m_voltageData;
    QVector<QVector<QVector<double>>> m_denoisedDataList;

    // 处理定时器
    QTimer* m_processingTimer;
    QTimer* m_dbUpdateTimer;

    // 状态变量
    int m_sampleCount;
    bool m_isFrameStarted;
    bool m_connected;
    bool m_acquiring;
    bool m_delayedVisualization;

    // 数据库工作线程
    QThread* m_dbThread;
    DatabaseWorker* m_dbWorker;

    // 可视化相关变量
    int m_frameCounter;
    int m_batchThreshold;
    QVector<QVector<QVector<double>>> m_visualBuffer; // 用于可视化的缓冲区
    qint64 m_lastTimestamp = 0;

    // 滤波器参数
    double m_lowCutoff;
    double m_highCutoff;
    double m_samplingRate;
    // 为每个通道单独存储历史数据
    QVector<QVector<double>> m_channelHistory;

    bool m_enableNotchFilter;    // 启用陷波滤波器标志
    double m_notchFrequency;     // 陷波频率（默认50Hz）
    double m_notchBandwidth;     // 陷波带宽
    bool m_enableHighpassFilter; // 启用高通滤波器标志

    int m_lastDisplayedIndex = 0;  // 最后显示的点在缓冲区中的全局索引
    qint64 m_baseTimestamp = 0;    // 缓冲区基准时间戳
    QVector<QPair<qint64, double>> m_displayBuffer; // 存储时间戳+FP1值


};

#endif // EEGDEVICE_H
